import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/hometar',
      name: 'hometar',
      component: () => import('@/views/HomeTar.vue'),

      children: [
        {
          path: '/about',
          name: 'about',
          component: () => import('@/views/AboutView.vue'),
        },
        {
          path: '/homeone',
          name: 'homeone',
          component: () => import('@/components/HomeOne.vue'),
        },

        {
          path: '/archive',
          name: 'archive',
          component: () => import('@/components/UserArchive.vue'),
        },

                {
          path: '/AdminArchive',
          name: 'AdminArchive',
          component: () => import('@/components/AdminArchive.vue'),
        },
        {
          path: '/logs',
          name: 'logs',
          component: () => import('@/components/Logs.vue'),
        },
        {
          path: '/personalcenter',
          name: 'personalcenter',
          component: () => import('@/components/PersonalCenter.vue'),
        },
        {
          path: '/task',
          name: 'task',
          component: () => import('@/components/TaskProcessing.vue'),
        },
        {
          path: '/group',
          name: 'group',
          component: () => import('@/components/Group.vue'),
        },
        {
          path: '/send/:id',
          name: 'send',
          component: () => import('@/components/Message.vue'),
          props: true,
        },
        {
          path: '/message',
          name: 'message',
          component: () => import('@/components/MessageSend.vue'),
        },
      ],
    },
    {
      path: '/',
      name: 'Login',
      component: () => import('@/components/Login.vue'),
    },
  ],
})

// **关键**：添加全局前置导航守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = !!localStorage.getItem('user-token')

  if (to.meta.requiresAuth && !isLoggedIn) {
    // 如果目标路由需要登录，但用户未登录，则跳转到登录页
    next({ name: 'Login' })
  } else if (to.name === 'Login' && isLoggedIn) {
    // 如果用户已登录，但试图访问登录页，则直接跳转到首页
    next({ name: 'Home' })
  } else {
    // 其他情况，正常放行
    next()
  }
})

export default router
